package com.weige.conver.service;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.weige.conver.utils.FileUtils;
import com.weige.conver.utils.RedisUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class RabbitMQService{

    @Value("${spring.rabbitmq.host}")
    private String host;
    @Value("${spring.rabbitmq.username}")
    private String userName;
    @Value("${spring.rabbitmq.password}")
    private String passWord;
    @Value("${spring.rabbitmq.port}")
    private Integer port;
    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;
    @Value("${CoverQueue}")
    private String CoverQueue;
    @Value("${RoutingKey}")
    private String RoutingKey;
    @Value("${Exchange}")
    private String Exchange;

    private ConnectionFactory factory = null;

    private Connection connection = null;

    private Channel channel = null;

    private boolean isMqConnect = false;

    @Autowired
    RedisUtils redisUtils;

    public void sendData(String msg,String devId,String devName,String model,String manufactureId,String serviceName) {
        String data = StringEscapeUtils.unescapeJavaScript(msg);
        //mq连接成功
        if (isMqConnect) {
            boolean ret = sendMsg2Mq(data, devId,devName, model,manufactureId,serviceName);
            if (false == ret) {
                getMqConnection();
            }
        } else {
            if (getMqConnection()) {
                sendMsg2Mq(data, devId,devName, model,manufactureId,serviceName);
            } else {
                System.out.println(getNowTime() + " Mq Connect Error!  请查看一下rabbitmq 服务运行状态！ 是否正常启动。");
            }

        }

    }

    public void freeMqConnection() {
        try {
            //关闭通道和连接
            this.channel.close();
            this.connection.close();
            this.factory = null;
            isMqConnect = false;

            System.out.println(getNowTime() + " freeMqConnection() ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getNowTime() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
        return sdf.format(date);
    }

    public boolean getMqConnection() {
        System.out.println(getNowTime() + "getMqConnection() ");

        try {
            //创建连接工厂
            this.factory = new ConnectionFactory();
            //设置RabbitMQ相关信息
            factory.setHost(host);
            factory.setUsername(userName);
            factory.setPassword(passWord);
            factory.setPort(port);
            factory.setVirtualHost(virtualHost);

            String queue = CoverQueue;

            //创建一个新的连接
            connection = factory.newConnection();
            //创建一个通道
            channel = connection.createChannel();

            channel.queueDeclare(queue, true, false, false, null);
            channel.queueBind(queue, Exchange, RoutingKey);

            isMqConnect = true;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(getNowTime() + "getMqConnection()  occure Exception!! " + e.toString());
        }

        return false;
    }

    private boolean sendMsg2Mq(String message, Object objectId,Object devName, String model,String manufactureId,String serviceName) {
        try {
            Map<String, Object> headers = new HashMap<String, Object>();
            headers.put("devId", objectId);
            headers.put("devName",devName);
            headers.put("manufactureId", manufactureId);
            headers.put("model", model);
            headers.put("serviceName", serviceName);
            AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().headers(headers).expiration("3600000").build();
            this.channel.basicPublish(Exchange, RoutingKey, properties, message.getBytes(StandardCharsets.UTF_8));
            return true;
        } catch (Exception e) {
            freeMqConnection();
            e.printStackTrace();
            System.out.println(getNowTime() + "sendmsg2Mq()  occure Exception!!  msg:" + message);
        }

        return false;
    }

}
